package com.cb2.algorithm.leetcode;

/**
 * <a href='https://leetcode.cn/problems/reverse-linked-list/'>反转链表(Reverse Linked List)</a>
 * <p>给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。 </p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：head = [1,2,3,4,5]
 *      输出：[5,4,3,2,1]
 *
 * 示例 2：
 *      输入：head = [1,2]
 *      输出：[2,1]
 *
 * 示例 3：
 *      输入：head = []
 *      输出：[]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>链表中节点的数目范围是 [0, 5000]</li>
 *         <li>-5000 <= Node.val <= 5000</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/31 15:22
 */
public class LC0206ReverseLinkedList_S {

    static class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null) {
                return null;
            }
            ListNode prevNode = null;
            ListNode currNode = head;
            ListNode nextNode;
            while (currNode != null) {
                nextNode = currNode.next;
                currNode.next = prevNode;
                prevNode = currNode;
                currNode = nextNode;
            }
            return prevNode;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        head1.next.next.next = new ListNode(4);
        head1.next.next.next.next = new ListNode(5);
        Printer.printListNode(solution.reverseList(head1));
        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(2);
        ListNode head3 = new ListNode(1);
        Printer.printListNode(solution.reverseList(head2));
        Printer.printListNode(solution.reverseList(head3));
        Printer.printListNode(solution.reverseList(null));
    }
}